package com.gw.youTubeAudioAPI.decode
{

	/**
	 * because flv's use backpointers following each FLVTag in the file, I can't find a
	 * way of parsing the file progressively forwards. This is a simple solution that seeks to 
	 * index the flv file by creating an array of progressive pointer positions
	 * of course this means the flv has to be downloaded first (which sucks) but I can't find anymore
	 * documentation to help me out :(
	 **/
	
	public dynamic class FLV_Index extends Array
	{
		private var index:int = -1;
		private var backPointerPos:int = 0;
		private var _flv:FLV_Wrapper;
		
		public function FLV_Index(flv:FLV_Wrapper)
		{
			super();
			this._flv = flv;
			backPointerPos = _flv.length;
			trace("indexing flv...");
			while (spiderTags());
		}
		private function spiderTags():Boolean
		{
			/*-FLV file body------------------------
			UI32		0	Prev Tag
			FLVTAG			First Tag
			UI32		11+	Size of prev tag
			FLVTAG			Second Tag
			UI32		11+	Size of pref tag
			*/
			
			var success:Boolean = true;
			backPointerPos -= SizeOf.UI32; //move back 32 bits
			_flv.position = backPointerPos;
			var backPointerVal:uint = _flv.readUI32();//read size of tag (position moves forward 32 bits)
			if (backPointerVal) //last pointer always returns 0
			{
				_flv.position = backPointerPos - backPointerVal;//read position of next backpointer
				backPointerPos = _flv.position;//update backpointer	
				if (_flv.readUI8() == 8) //if this is an audio tag add to index
					this.unshift(backPointerPos);//re-index as we go
			}
			else 
			{
				success = false;
			}
			return success
		}	
		public function getNextPointer():int
		{
			var index:int = ++index > this.length ? this.length : index;
			return this[index];	
		}
		/*
		public function get prevPointer():int
		{
			return this[index-- < 0 ? 0 : index];	
		}
		*/
	}
}